package models

import (
	"github.com/astaxie/beego/orm"
	"strconv"
)

type ConfigRanking struct {
	ChannelType int8 `orm:"column(channel_type)" description:"频道类型"`
	RankId      int  `orm:"column(rank_id)" description:"排行榜ID"`
	BookId      int  `orm:"column(book_id)" description:"小说ID"`
	SortId      int  `orm:"column(sort_id);auto" description:"排序ID"`
}

type RankList struct {
	Sort     int
	RankName string
	Name     string
	ConfigRanking
}

func (t *ConfigRanking) TableName() string {
	return "config_ranking"
}

func init() {
	orm.RegisterModel(new(ConfigRanking))
}

func GetRankList(page int, pageSize int, channel int8, rank int) ([]*RankList, int) {
	o := orm.NewOrm()
	offset := (page - 1) * pageSize
	rankLists := make([]*RankList, 0)
	total := 0
	sqlStr := "SELECT b.name,cr.*,sr.rank_name FROM book b,config_ranking cr,sys_rnk sr WHERE sr.id = cr.rank_id AND cr.book_id = b.id AND cr.channel_type = ? AND cr.rank_id = ? order by cr.sort_id asc limit " + strconv.Itoa(offset) + "," + strconv.Itoa(pageSize)
	o.Raw(sqlStr, channel, rank).QueryRows(&rankLists)

	sqlCount := "SELECT count(*) FROM book b,config_ranking cr,sys_rnk sr WHERE sr.id = cr.rank_id AND cr.book_id = b.id AND cr.channel_type = ? AND cr.rank_id = ?"
	o.Raw(sqlCount, channel, rank).QueryRow(&total)

	for k,v := range rankLists {
		v.Sort = k + 1
	}

	return rankLists, total
}

func AddRankBook(bookId int, channel int8, rankId int) error {
	o := orm.NewOrm()
	sortIds := make([]int, 0)
	o.Raw("select sort_id from config_ranking where channel_type = ? and rank_id = ? order by sort_id desc", channel, rankId).QueryRows(&sortIds)
	sortId := 1
	if len(sortIds) != 0 {
		sortId = sortIds[0] + 1
	}
	configRanking := &ConfigRanking{
		ChannelType: channel,
		RankId:      rankId,
		BookId:      bookId,
		SortId:      sortId,
	}
	_, err := o.Insert(configRanking)
	if err != nil {
		return err
	}
	return nil
}

func UpdateConfigRanking(bookId int, channel int8, rankId int, sortId int) error {
	o := orm.NewOrm()
	_, err := o.Raw("update config_ranking set book_id = ? where channel_type = ? and rank_id = ? and sort_id = ?", bookId, channel, rankId, sortId).Exec()
	if err != nil {
		return err
	}
	return nil
}

func DelConfigRanking(bookId int, channel int8, rankId int, sortId int) error {
	o := orm.NewOrm()
	_, err := o.Raw("delete from config_ranking where book_id = ? and channel_type = ? and rank_id = ? and sort_id = ?", bookId, channel, rankId, sortId).Exec()
	if err != nil {
		return err
	}
	return nil
}

func EmptyConfigRanking(channel int8, rankId int) error {
	o := orm.NewOrm()
	_, err := o.Raw("delete from config_ranking where channel_type = ? and rank_id = ? ", channel, rankId).Exec()
	if err != nil {
		return err
	}
	return nil
}
